package com.gack.business.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;


/**
 * 
 * @author ws
 * 2018-5-31
 */
@Repository
public class ContactsDao {

	@PersistenceContext
	private EntityManager em;
	
	/**
	 * 查询用户id对应的好友备注
	 * @param userIdList 用户id集合
	 * @param userId 用户id
	 * @return
	 */
	public List<Object[]> findUserIdAndFriendRemarks(List<String> userIdList, String userId){
		if(userIdList == null || userIdList.size() == 0){
			return new ArrayList<Object[]>();
		}
		
		String jpql = "select c.userid_friend_id, c.friend_remarks"
				+ " from contacts c"
				+ " where c.type = 1"
				+ " and c.friend_remarks is not null"
				+ " and trim(c.friend_remarks) != ''"
				+ " and c.user_username = (select u.username"
											+ " from user u"
											+ " where u.id = :userId)"
				+ " and c.userid_friend_id in (select u1.id"
											+ " from user u1"
											+ " where u1.id in ";
		StringBuilder sb = new StringBuilder();
		sb.append("(");
		for(String t : userIdList){
			 sb.append(" '" + t + "',");
		}
		sb = new StringBuilder(sb.substring(0, sb.length()-1));//去掉最后的","
		sb.append(") )");//最后一个括号是子查询的右括号
		
		jpql += sb.toString();
		
		Query query = em.createNativeQuery(jpql);
		query.setParameter("userId", userId);
		List<Object[]> list = query.getResultList();
		
		return list;
	}
	
	/**
	 * 修改某用户的好友备注为空
	 * @param userId 被修改者id
	 * @param operatorId 操作者id
	 * @return
	 */
	public int setFriendRemarksNull(String userId, String operatorId){
		String jpql = "update contacts"
				+ " set friend_remarks = null"
				+ " where userid_friend_id=:userId"
				+ " and user_userid=:operatorId"
				+ " and type=1";
		
		Query query = em.createNativeQuery(jpql);
		query.setParameter("userId", userId);
		query.setParameter("operatorId", operatorId);
		return query.executeUpdate();
	}
	
}
